
using System;
using System.Data;
using System.Collections;
using System.Data.SqlClient;
using StringHelper = Widgetsphere.Core.Util.StringHelper;
using System.Collections.Generic;

namespace Widgetsphere.Core.DataAccess
{
	public partial class ParameterHelper
	{
		#region member variables
		static ParameterHelper _instance = null;
		#endregion 

		#region Constants
		private const string ORIGINAL_PREFIX = "Original_";
		private const string DATABASE_WORD_SEPERATOR = "_";
		private const string PARAMETER_DECLARATION = "@";
		private const string RETURN_VALUE_NAME = "@RETURN_VALUE";
		#endregion

		#region Enums
		internal enum ParameterType
		{
			Integer = 0,
			VarChar = 1,
			NVarChar = 2,
			Text = 3,
			Float = 4,
			Boolean = 5,
			DateTime = 6,
			Timestamp = 7,
			Char = 8,
			NText = 9,
		}
		internal enum ParameterMode
		{
			IN = 0,
			OUT = 1,
			INOUT = 2,
		}
		#endregion

		#region Constructor
		private ParameterHelper()
		{
		}
		#endregion
		
		internal static ParameterHelper GetInstance()
		{
			if (_instance == null)
			{
				_instance = new ParameterHelper();
			}
			return _instance;
		}


		#region Build Parameters On The Fly
		internal List<IDbDataParameter> GetDataSetParameterArray(string connectionString, string storedProcedureName)
		{
			List<IDbDataParameter> paramCollection = null;
			try
			{
				IDbDataParameter[] parameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, storedProcedureName);
				paramCollection = BuildParameterCollection(parameters, true);
			}
			catch (Exception ex)
			{
				throw ex;
			}
			return paramCollection;
		}

		internal List<IDbDataParameter> GetDirectQueryParameterCollection(string connectionString, string storedProcedureName)
		{
			List<IDbDataParameter> paramCollection = null;
			try
			{
				IDbDataParameter[] parameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, storedProcedureName);
				paramCollection = BuildParameterCollection(parameters, false);
			}
			catch (Exception ex)
			{
				throw ex;
			}
			return paramCollection;
		}

		private List<IDbDataParameter> BuildParameterCollection(IDbDataParameter[] parameters, bool dataTableParameter)
		{
			List<IDbDataParameter> paramCollection = new List<IDbDataParameter>();
			foreach (IDbDataParameter parameter in parameters)
			{
				if (dataTableParameter && !StringHelper.Match(parameter.ParameterName, RETURN_VALUE_NAME, false))
				{
					if (parameter.ParameterName.StartsWith(PARAMETER_DECLARATION + ORIGINAL_PREFIX))
					{
						parameter.SourceColumn = this.ParameterNameToDataColumnName(parameter.ParameterName);
						parameter.SourceVersion = DataRowVersion.Original;
					}
					else
					{
						parameter.SourceColumn = this.ParameterNameToDataColumnName(parameter.ParameterName);
						parameter.SourceVersion = DataRowVersion.Current;
					}
				}
				paramCollection.Add(parameter);
			}
			return paramCollection;
		}


		internal IDbDataParameter BuildParameter(string parameterName, ParameterType paramType, int parameterSize, ParameterMode parameterMode, bool dataTableParameter)
		{
			IDbDataParameter returnParam = null;
			if (dataTableParameter)
			{
				if (parameterName.StartsWith(ORIGINAL_PREFIX))
				{
					parameterName = parameterName.Remove(0, ORIGINAL_PREFIX.Length);
					returnParam = this.ParameterInputDataRowOriginal(parameterName, paramType, parameterSize, true);
				}
				else if (StringHelper.Match(parameterName, RETURN_VALUE_NAME, false))
				{
					returnParam = this.ParameterReturnValue();
				}
				else 
				{
					returnParam = this.ParameterInputDataRowCurrent(parameterName, paramType, parameterSize, true);
				}
			}
			else
			{
				switch (parameterMode)
				{
					case ParameterMode.IN: returnParam = this.ParameterInput(parameterName, paramType, parameterSize, null);break;
					case ParameterMode.OUT:returnParam = returnParam = this.ParameterOutput(parameterName, paramType, parameterSize, null);break;
					case ParameterMode.INOUT:returnParam = this.ParameterInputOutput(parameterName, paramType, parameterSize, null);break;
				}
			}
			return returnParam;
		}
		#endregion

		#region private helper methods for string conversion
		private string ParameterNameToDataColumnName(string parameterName)
		{
			string originalStartString = PARAMETER_DECLARATION + ORIGINAL_PREFIX;
			if (parameterName.StartsWith(originalStartString))
			{
				parameterName = parameterName.Remove(0,originalStartString.Length);
			}
			else
			{
				parameterName = parameterName.Remove(0, 1);
			}
			return parameterName.ToLower();
		}

		private string CamelCaseColumnName(string columnName)
		{
			int databaseWordSeperatorIndex = 0;
			columnName = columnName.ToLower();
			
			while (databaseWordSeperatorIndex != -1)
			{
				databaseWordSeperatorIndex = columnName.IndexOf(DATABASE_WORD_SEPERATOR);
				if (databaseWordSeperatorIndex != -1)
				{
					columnName = columnName.Remove(databaseWordSeperatorIndex, 1);
					columnName = columnName.Insert(databaseWordSeperatorIndex, columnName.Substring(databaseWordSeperatorIndex,1).ToUpper());
					columnName = columnName.Remove(databaseWordSeperatorIndex, 1);
				}
			}
			return columnName;
		}

		private string PascalCaseColumnName(string columnName)
		{
			int databaseWordSeperatorIndex = 0;
			columnName = columnName.ToLower();
			columnName = columnName.Insert(0, columnName.Substring(0,1).ToUpper());
			columnName = columnName.Remove(1,1);
			
			while (databaseWordSeperatorIndex != -1)
			{
				databaseWordSeperatorIndex = columnName.IndexOf(DATABASE_WORD_SEPERATOR);
				if (databaseWordSeperatorIndex != -1)
				{
					columnName = columnName.Remove(databaseWordSeperatorIndex, 1);
					columnName = columnName.Insert(databaseWordSeperatorIndex, columnName.Substring(databaseWordSeperatorIndex,1).ToUpper());
					columnName = columnName.Remove(databaseWordSeperatorIndex + 1, 1);
				}
			}
			return columnName;
		}
		#endregion 

		#region Private helper methods creating parameters
		private IDbDataParameter ParameterInput(string paramName, ParameterType type, int size, object inValue)
		{
			return Parameter(paramName, type, size, ParameterDirection.Input, inValue);
		}

		private IDbDataParameter ParameterInputOutput(string paramName, ParameterType type, int size, object inValue)
		{
			return Parameter(paramName, type, size, ParameterDirection.InputOutput, inValue);
		}

		private IDbDataParameter ParameterOutput(string paramName, ParameterType type, int size, object inValue)
		{
			return Parameter(paramName, type, size, ParameterDirection.Output, inValue);
		}

		private IDbDataParameter ParameterReturnValue()
		{
			IDbDataParameter dbParam;
			dbParam = Parameter(RETURN_VALUE_NAME, ParameterType.Integer, 4, ParameterDirection.ReturnValue, true, String.Empty, DataRowVersion.Current, null);
			return dbParam;
		}
		
		private IDbDataParameter ParameterInputDataRowOriginal(string columnName, ParameterType type, int size, bool isNullable)
		{
			string parameterName = PARAMETER_DECLARATION + ORIGINAL_PREFIX + columnName;
			string sourceColumn = columnName;
			return Parameter(parameterName, type, size, ParameterDirection.Input, isNullable, sourceColumn, DataRowVersion.Original);
		}
		private IDbDataParameter ParameterInputDataRowCurrent(string columnName, ParameterType type, int size, bool isNullable)
		{
			string parameterName = PARAMETER_DECLARATION + columnName;
			string sourceColumn = columnName;
			return Parameter(parameterName, type, size, ParameterDirection.Input, isNullable, sourceColumn, DataRowVersion.Current);
		}
		private IDbDataParameter Parameter(string paramName, ParameterType type, int size, ParameterDirection parameterDirection, object inValue)
		{
			IDbDataParameter dbParam;
			string parameterName = PARAMETER_DECLARATION + paramName;
			string sourceColumn = String.Empty;
			if (inValue != null)
			{
				dbParam = Parameter(parameterName, type, size, ParameterDirection.Input, false, sourceColumn, DataRowVersion.Current, inValue);
			}
			else
			{
				dbParam = Parameter(parameterName, type, size, ParameterDirection.Input, true, sourceColumn, DataRowVersion.Current, inValue);
			}
			return dbParam;
		}
		private IDbDataParameter Parameter(string parameterName, ParameterType type, int size, ParameterDirection direction, bool isNullable, string sourceColumn, DataRowVersion rowVersion, object inValue)
		{
			return Parameter(parameterName, type, size, direction, ((System.Byte)(0)), ((System.Byte)(0)), isNullable, sourceColumn, rowVersion, inValue);
		}
		private IDbDataParameter Parameter(string parameterName, ParameterType type, int size, ParameterDirection direction, bool isNullable, string sourceColumn, DataRowVersion rowVersion)
		{
			return Parameter(parameterName, type, size, direction, isNullable, sourceColumn, rowVersion, null);
		}

		private int GetTypeSize(ParameterType paramType)
		{
			int paramSize;
			switch (paramType)
			{
				case ParameterType.Boolean: paramSize=1; break;
				case ParameterType.DateTime: paramSize=8; break;
				case ParameterType.Float: paramSize=8; break;
				case ParameterType.Integer: paramSize=4; break;
				case ParameterType.NVarChar: paramSize=1; break;
				case ParameterType.Text: paramSize=16; break;
				case ParameterType.VarChar: paramSize=1; break;
				case ParameterType.Timestamp: paramSize=8; break;
				case ParameterType.Char: paramSize=1;break;
				case ParameterType.NText: paramSize=16;break;
				default : throw new Exception("The parameter type " + paramType.ToString() + " is not currently supoorted");
			}
			return paramSize;
		}
		
		#region SQL
		internal IDbDataParameter GetParameterClone(IDbDataParameter paramToClone)
		{
			SqlParameter sqlParamToClone = (SqlParameter) paramToClone;
			SqlParameter returnParam = this.Parameter(sqlParamToClone.ParameterName, sqlParamToClone.SqlDbType, 
																								sqlParamToClone.Size, sqlParamToClone.Direction, 
																								sqlParamToClone.Precision, sqlParamToClone.Scale, 
																								true, sqlParamToClone.SourceColumn, 
																								sqlParamToClone.SourceVersion, sqlParamToClone.Value);
			return returnParam;
		}

		private IDbDataParameter Parameter(string parameterName, ParameterType type, int size, ParameterDirection direction, byte precision, byte scale, bool isNullable, string sourceColumn, DataRowVersion rowVersion, object inValue)
		{
			IDbDataParameter dbParam = Parameter(parameterName, GetSqlType(type), size, direction, precision, scale, isNullable, sourceColumn, rowVersion, inValue);
			return dbParam;
		}

		private SqlParameter Parameter(string parameterName, SqlDbType type, int size, ParameterDirection direction, byte precision, byte scale, bool isNullable, string sourceColumn, DataRowVersion rowVersion, object inValue)
		{
			SqlParameter dbParam = new SqlParameter(parameterName, type, size, direction, isNullable, precision, scale, sourceColumn, rowVersion, inValue);
			return dbParam;
		}
		private SqlDbType GetSqlType(ParameterType genericType)
		{
			SqlDbType sqlType;
			switch (genericType)
			{
				case ParameterType.Boolean: sqlType=SqlDbType.Bit; break;
				case ParameterType.DateTime: sqlType=SqlDbType.DateTime; break;
				case ParameterType.Float: sqlType=SqlDbType.Float; break;
				case ParameterType.Integer: sqlType=SqlDbType.Int; break;
				case ParameterType.NVarChar: sqlType=SqlDbType.NVarChar; break;
				case ParameterType.Text: sqlType=SqlDbType.Text; break;
				case ParameterType.VarChar: sqlType=SqlDbType.VarChar; break;
				case ParameterType.Timestamp: sqlType=SqlDbType.Timestamp; break;
				case ParameterType.Char: sqlType=SqlDbType.Char; break;
				case ParameterType.NText: sqlType=SqlDbType.NText; break;
				default : throw new Exception("The parameter type " + genericType.ToString() + " is not currently supoorted");
			}
			return sqlType;
		}
		#endregion
		#endregion

	}

	#region SqlParameterHelper
	/// <summary>
	/// SqlHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
	/// ability to discover parameters for stored procedures at run-time.
	/// </summary>
	public sealed partial class SqlHelperParameterCache
	{
		#region private methods, variables, and constructors

		//Since this class provides only static methods, make the default constructor private to prevent 
		//instances from being created with "new SqlHelperParameterCache()"
		private SqlHelperParameterCache() {}

		private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());

		/// <summary>
		/// Resolve at run time the appropriate set of SqlParameters for a stored procedure
		/// </summary>
		/// <param name="connection">A valid SqlConnection object</param>
		/// <param name="spName">The name of the stored procedure</param>
		/// <param name="includeReturnValueParameter">Whether or not to include their return value parameter</param>
		/// <returns>The parameter array discovered.</returns>
		private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
		{
			if( connection == null ) throw new ArgumentNullException( "connection" );
			if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

			SqlCommand cmd = new SqlCommand(spName, connection);
			cmd.CommandType = CommandType.StoredProcedure;

			connection.Open();
			SqlCommandBuilder.DeriveParameters(cmd);
			connection.Close();

			if (!includeReturnValueParameter) 
			{
				cmd.Parameters.RemoveAt(0);
			}

			SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];

			cmd.Parameters.CopyTo(discoveredParameters, 0);

			// Init the parameters with a DBNull value
			foreach (SqlParameter discoveredParameter in discoveredParameters)
			{
				discoveredParameter.Value = DBNull.Value;
			}
			return discoveredParameters;
		}

		/// <summary>
		/// Deep copy of cached SqlParameter array
		/// </summary>
		/// <param name="originalParameters"></param>
		/// <returns></returns>
		private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
		{
			SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];

			for (int i = 0, j = originalParameters.Length; i < j; i++)
			{
				clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
			}

			return clonedParameters;
		}
		#endregion private methods, variables, and constructors

		#region caching functions

		/// <summary>
		/// Add parameter array to the cache
		/// </summary>
		/// <param name="connectionString">A valid connection string for a SqlConnection</param>
		/// <param name="commandText">The stored procedure name or T-SQL command</param>
		/// <param name="commandParameters">An array of SqlParamters to be cached</param>
		public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
		{
			if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
			if( commandText == null || commandText.Length == 0 ) throw new ArgumentNullException( "commandText" );

			string hashKey = connectionString + ":" + commandText;

			paramCache[hashKey] = commandParameters;
		}

		/// <summary>
		/// Retrieve a parameter array from the cache
		/// </summary>
		/// <param name="connectionString">A valid connection string for a SqlConnection</param>
		/// <param name="commandText">The stored procedure name or T-SQL command</param>
		/// <returns>An array of SqlParamters</returns>
		public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
		{
			if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
			if( commandText == null || commandText.Length == 0 ) throw new ArgumentNullException( "commandText" );

			string hashKey = connectionString + ":" + commandText;

			SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[];
			if (cachedParameters == null)
			{			
				return null;
			}
			else
			{
				return CloneParameters(cachedParameters);
			}
		}
		#endregion caching functions

		#region Parameter Discovery Functions

		/// <summary>
		/// Retrieves the set of SqlParameters appropriate for the stored procedure
		/// </summary>
		/// <remarks>
		/// This method will query the database for this information, and then store it in a cache for future requests.
		/// </remarks>
		/// <param name="connectionString">A valid connection string for a SqlConnection</param>
		/// <param name="spName">The name of the stored procedure</param>
		/// <returns>An array of SqlParameters</returns>
		public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
		{
			return GetSpParameterSet(connectionString, spName, true);
		}

		/// <summary>
		/// Retrieves the set of SqlParameters appropriate for the stored procedure
		/// </summary>
		/// <remarks>
		/// This method will query the database for this information, and then store it in a cache for future requests.
		/// </remarks>
		/// <param name="connectionString">A valid connection string for a SqlConnection</param>
		/// <param name="spName">The name of the stored procedure</param>
		/// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
		/// <returns>An array of SqlParameters</returns>
		public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
		{
			if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
			if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

			using(SqlConnection connection = new SqlConnection(connectionString))
			{
				return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter);
			}
		}

		/// <summary>
		/// Retrieves the set of SqlParameters appropriate for the stored procedure
		/// </summary>
		/// <remarks>
		/// This method will query the database for this information, and then store it in a cache for future requests.
		/// </remarks>
		/// <param name="connection">A valid SqlConnection object</param>
		/// <param name="spName">The name of the stored procedure</param>
		/// <returns>An array of SqlParameters</returns>
		internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName)
		{
			return GetSpParameterSet(connection, spName, false);
		}

		/// <summary>
		/// Retrieves the set of SqlParameters appropriate for the stored procedure
		/// </summary>
		/// <remarks>
		/// This method will query the database for this information, and then store it in a cache for future requests.
		/// </remarks>
		/// <param name="connection">A valid SqlConnection object</param>
		/// <param name="spName">The name of the stored procedure</param>
		/// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
		/// <returns>An array of SqlParameters</returns>
		internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
		{
			if( connection == null ) throw new ArgumentNullException( "connection" );
			using (SqlConnection clonedConnection = (SqlConnection)((ICloneable)connection).Clone())
			{
				return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter);
			}
		}

		/// <summary>
		/// Retrieves the set of SqlParameters appropriate for the stored procedure
		/// </summary>
		/// <param name="connection">A valid SqlConnection object</param>
		/// <param name="spName">The name of the stored procedure</param>
		/// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
		/// <returns>An array of SqlParameters</returns>
		private static SqlParameter[] GetSpParameterSetInternal(SqlConnection connection, string spName, bool includeReturnValueParameter)
		{
			if( connection == null ) throw new ArgumentNullException( "connection" );
			if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

			string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter":"");

			SqlParameter[] cachedParameters;

			cachedParameters = paramCache[hashKey] as SqlParameter[];
			if (cachedParameters == null)
			{	
				SqlParameter[] spParameters = DiscoverSpParameterSet(connection, spName, includeReturnValueParameter);
				paramCache[hashKey] = spParameters;
				cachedParameters = spParameters;
			}

			return CloneParameters(cachedParameters);
		}
		#endregion Parameter Discovery Functions
	}
	#endregion

}
